import { BlueshellState } from "@konghayao/blueshell";
import { random } from "game-random";
import createBehaviorTree, { EVENT } from "behavior-core";
import SlimeBehavior from "./Slime.json";

const Behavior: EVENT<Slime> = {
    isWeak(state) {
        // console.log("是否虚弱");
        return state.HP < 30;
    },
    beFounded(state) {
        // console.log("是否被发现");
        if ((window as any).player) {
            return (
                Math.abs((window as any).player.x - state.x) < 200 &&
                Math.abs((window as any).player.y - state.y) < 200
            );
        }
        return false;
    },
    attack(state) {
        console.log("attack");
        return true;
    },
    escape(state) {
        console.log("escape");
        state.jump(-1);
        return true;
    },
    Normal(state) {
        console.log("normal");
        state.jump(Math.random() - 0.5 > 0 ? 1 : -1);
        return true;
    },
};
const { BT, State } = createBehaviorTree<Slime>(SlimeBehavior);

export class Slime extends Laya.Sprite implements BlueshellState {
    constructor() {
        super();

        this.frameLoop(200, null, () => {
            BT.handleEvent(this, Behavior);
            console.log("史莱姆跳跃中");
        });
    }
    HP = 100;
    isAngry = false;
    errorReason?: Error | undefined;
    __blueshell: any;
    beginJump!: Laya.FrameAnimation;
    jump(toPlayer = 1) {
        const RigidBody = this.getComponent(Laya.RigidBody) as Laya.RigidBody;

        this.beginJump.play();
        RigidBody.applyLinearImpulseToCenter({
            x: random(0, 50) * (Behavior.beFounded(this) ? -1 : 1) * toPlayer,
            y: -70,
        });

        return true;
    }
}
